package edu.upc.autopartescybershop.web;

import edu.upc.autopartescybershop.domain.Marca;
import edu.upc.autopartescybershop.service.MarcaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Carlos
 */
@Controller
public class MarcasController
{

    @Autowired
    MarcaService marcaService;

    @RequestMapping(value = "/marcas.htm", method = RequestMethod.GET)
    public ModelAndView listadoMarcas()
    {
        ModelAndView mav = new ModelAndView("marcas");
        mav.addObject("listadoMarcas", marcaService.obtenerMarcas());
        return mav;
    }

    @RequestMapping(value = "/marcas_form.htm", method = RequestMethod.GET)
    public
    @ModelAttribute("marca")
    Marca setupForm(@RequestParam("accion") String accion, @RequestParam("id") int codigoMarca)
    {
        if (accion.equals("E"))
        {
            return marcaService.obtenerMarca(codigoMarca);
        }
        else if (accion.equals("D"))
        {
            Marca marca = marcaService.obtenerMarca(codigoMarca);
            marca.setNombre("-*D*-");
            return marca;
        }
        else if (accion.equals("N"))
        {
            return new Marca();
        }
        else
        {
            return null;
        }
    }

    @RequestMapping(value = "/marcas_form.htm", method = RequestMethod.POST)
    public String onsubmit(@ModelAttribute("marca") Marca marca,
            BindingResult result, SessionStatus status, @RequestParam("accion") String accion, @RequestParam("id") int codigoMarca)
    {
        if (accion.equals("E") || accion.equals("N"))
        {
            marcaService.grabarMarca(marca);
        }
        else if (accion.equals("D"))
        {
            marcaService.eliminarMarca(codigoMarca);
        }
        return "redirect:/marcas.htm";
    }
}
